#!/usr/bin/env Rscript
# -*- coding: utf-8 -*-
#
# @File    : plot_top_taxa_boxplot.R
# @Description: 根据 top N 分类单元（species/genus/phylum 等）RPM 绘制箱线图，并按照分组着色，显示检出率标签

suppressPackageStartupMessages({
  library(optparse)
  library(tidyverse)
  library(ggplot2)
  library(ggsci)
})

# --------------------------
# 命令行参数解析
# --------------------------
option_list <- list(
  make_option(c("-i", "--input"), type = "character", help = "输入长表格文件（包含分类列、Sample、RPM、Group、label）"),
  make_option(c("--pdf"), type = "character", help = "输出 PDF 文件路径"),
  make_option(c("--png"), type = "character", help = "输出 PNG 文件路径"),
  make_option(c("--width"), type = "numeric", default = 16, help = "图宽度 (inch)"),
  make_option(c("--height"), type = "numeric", default = 8, help = "图高度 (inch)"),
  make_option(c("--dpi"), type = "numeric", default = 300, help = "PNG 输出分辨率")
)

opt_parser <- OptionParser(option_list = option_list)
opt <- parse_args(opt_parser)

# --------------------------
# 读取数据
# --------------------------
df <- read.csv(opt$input, sep = "\t", check.names = FALSE)

# 自动检测第一个列名作为分类列（可能是 species、genus、phylum 等）
tax_col <- colnames(df)[1]

if (!all(c("Sample", "RPM", "Group") %in% colnames(df))) {
  stop("输入文件缺少必要列：Sample, RPM, Group")
}

# --------------------------
# 数据预处理
# --------------------------
df$RPM <- log10(df$RPM + 1)

# 获取每个分类唯一 label
label_df <- df %>%
  distinct(!!sym(tax_col), label) %>%
  group_by(!!sym(tax_col)) %>%
  slice(1) %>%
  ungroup()

# 计算每个分类的最大值，用于放置文字
y_pos <- df %>%
  group_by(!!sym(tax_col)) %>%
  summarise(y = max(RPM, na.rm = TRUE) * 1.05)

label_df <- left_join(label_df, y_pos, by = tax_col)

# --------------------------
# 绘图
# --------------------------
p <- ggplot(df, aes_string(x = tax_col, y = "RPM", fill = "Group")) +
  geom_boxplot(outlier.shape = NA) +
  theme_bw() +
  scale_fill_jama() +
  labs(
    x = NULL,
    y = "Log10(RPM + 1)",
    title = paste("Top", tax_col, "RPM by Group")
  ) +
  theme(
    axis.text.x = element_text(angle = 60, hjust = 1, vjust = 1, size = 14),
    axis.text.y = element_text(size = 14),
    plot.title = element_text(hjust = 0.5)
  ) +
  geom_text(
    data = label_df,
    aes_string(x = tax_col, y = "y", label = "label"),
    inherit.aes = FALSE,
    vjust = -0.3,
    size = 4,
    color = "black"
  )

# --------------------------
# 保存文件
# --------------------------
ggsave(opt$pdf, plot = p, width = opt$width, height = opt$height)
ggsave(opt$png, plot = p, width = opt$width, height = opt$height, dpi = opt$dpi)

message("输出完成")
message("PDF 文件: ", opt$pdf)
message("PNG 文件: ", opt$png)
